package cn.edu.scau.cmi.ema.util;
/**
 * 
 * @author Liang Zaoqing
 * 提供几个基本的功能，例如用于单个元素集合的内容获取
 */

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.edu.scau.cmi.ema.domain.Crawlerdetect;

public class CmiTimeUtil {
	/**
	 * 生成时间戳
	 * @param dateObj 时间对象
	 * @param pattern 时间格式模式
	 * @return
	 */
	public static String timeStampToFormatDate(Object dateObj, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String formatDate = sdf.format(dateObj);
        return formatDate;
    }
	

//	把页面中的日期转换成为年月日的格式的Calendar
//	把2021-08-16格式的时间字符串封装为Calendar
	public static Calendar getYMDCalendar(String calendarString) {
		String[] startTimeStrings = calendarString.split("-");
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, Integer.parseInt(startTimeStrings[0]));
		calendar.set(Calendar.MONTH, Integer.parseInt(startTimeStrings[1])-1);//注意：calendar的月是从0开始，1表示二月。
		calendar.set(Calendar.DATE, Integer.parseInt(startTimeStrings[2]));
		return calendar;
		
	}
	
//	把2021-08-16 22:14:28格式的时间字符串封装为Calendar
	public static Calendar getYMDHMSCalendar(String calendarString) {
		Calendar calendar = Calendar.getInstance();
		String[] times = calendarString.split(" ");
//		2021-08-16
		String[] startDateStrings = times[0].split("-");
		
		calendar.set(Calendar.YEAR, Integer.parseInt(startDateStrings[0]));
		calendar.set(Calendar.MONTH, Integer.parseInt(startDateStrings[1])-1);//注意：calendar的月是从0开始，1表示二月。
		calendar.set(Calendar.DATE, Integer.parseInt(startDateStrings[2]));
//		22:14:28
		String[] startTimeStrings = times[1].split(":");
		calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTimeStrings[0]));
		calendar.set(Calendar.MINUTE, Integer.parseInt(startTimeStrings[1]));
		calendar.set(Calendar.SECOND, Integer.parseInt(startTimeStrings[2]));
		return calendar;
	}
	
	
	
	
	
	
//	返回文件的时间戳，方便查看文件的管理
	public static String getYMDHMSString(Calendar calendar) {
		String timeString = calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月"
				+ calendar.get(Calendar.DATE) + "日" + calendar.get(Calendar.HOUR) + "时" + calendar.get(Calendar.MINUTE) + "分";

		return timeString;
	}
	
//	格式：2020-8-25      把页面中的日期转换成为年月日的格式的Calendar
	public static String getYMDString(Calendar calendar) {
		//注意：calendar的月是从0开始，1表示二月。
		return calendar.get(Calendar.YEAR)+"年"+ (calendar.get(Calendar.MONTH)+1)+"月"+calendar.get(Calendar.DATE)+ "日";		
		
	}
	/*
	 * // 格式：2020年-8月-25日 public static String getTimeString(Calendar storeInTime) {
	 * return storeInTime.get(Calendar.YEAR) + "年" +
	 * (storeInTime.get(Calendar.MONTH) + 1) + "月" + storeInTime.get(Calendar.DATE)
	 * + "日-"; }
	 */
//	TODO 2020-11-20，待完善！！！
//	从excel中读取的时间，例如是2020年10月20号，得到的结果是38800，直接设置为calendar或者date,将是2127年的一个时间，原因待查，现在使用该方法去完成功能。
//	2006年4月13号-》2024-11-17
	
	public static Calendar cast2Calendar(String timeStr) {
        int da = Integer.parseInt(timeStr.split("\\.")[0]) - 44105;
		
		Date dat = new Date();
		dat.setDate(da);
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(dat);
		
		return calendar;
	}
	
	public static Calendar castZwzDateString2Calendar(String timeStr) {
        int da = Integer.parseInt(timeStr.split("\\.")[0]) - 44500;//469
		
		Date dat = new Date();
		dat.setDate(da);
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(dat);
		
		return calendar;
	}
	
	public static Calendar castZxlDateString2Calendar(String timeStr) {
        int da = Integer.parseInt(timeStr.split("\\.")[0]) - 44500;//469
		
		Date dat = new Date();
		dat.setDate(da);
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(dat);
		
		return calendar;
	}
	
	
	public static void test() {
		Calendar time = Calendar.getInstance();
		System.out.println(time);
	}
	
	public static void main(String[] args) {
		test();

	}
	
	public static String format(String oriangeProducedate) {
//		productdateType: 123456.6, 2019.12.30, 2019-12-32, 2019/12/32, 2019-12-32（检查日期）, 2.0190714E7
//		判断numbernic
		String producedate = "";
		
		String copyProducedate = new String(oriangeProducedate);
		
		String year = "";
		String month = "";
		String day = "";
		
		String[] divisionDateStrings = new String[5];
		
		String pattern = "\\d{5}.\\d";
		boolean isNumbernic = Pattern.matches(pattern , oriangeProducedate);
		if(isNumbernic) {
			double dDdate = Double.parseDouble(oriangeProducedate);
			int date = (int)dDdate;
			System.out.println("日期：" + date);
			
//			Calendar calendar = Calendar.getInstance();
	//		时间格式
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			
			Date parseDate = null;
			try {
				parseDate = dateFormat.parse("1900-01-01");
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//			calendar.setTime(parseDate);
//			
//			String format = dateFormat.format(calendar.getTime());	// 1990-01-01
//			System.out.println(format);
			
			Date importDate = CmiTimeUtil.addDate(parseDate, date);
			System.out.println(dateFormat.format(importDate));
			producedate = dateFormat.format(importDate);
			return producedate;
		}
//		oriangeProducedate = oriangeProducedate.replace("E7", "");//2.0190715E7
		
		else {
//			月份和日期格式不准确的情况
			oriangeProducedate = oriangeProducedate.replaceAll("[^x00-xff[-/ ]]", "").trim();
			if(oriangeProducedate.length() == 6) {
				year = oriangeProducedate.substring(0, 4);
				month = oriangeProducedate.substring(4, 5);
				day = oriangeProducedate.substring(5, 6);
				producedate = year + "-0" + month + "-0" + day;
				return producedate;
			}else if(oriangeProducedate.length() == 7) {
				int index = 0;
//				截取数字
				Pattern pat = Pattern.compile("\\d+");
				Matcher matcher = pat.matcher(copyProducedate);
				while(matcher.find()) {
					divisionDateStrings[index] = new String(matcher.group(0));
					index++;
				}
//				如果月份不是两位数，就在月份加0，否则就日期加0
				if(Integer.parseInt(divisionDateStrings[1]) <= 9 ) {
					year = oriangeProducedate.substring(0, 4);
					month = oriangeProducedate.substring(4, 5);
					day = oriangeProducedate.substring(5, 7);
					producedate = year + "-0" + month + "-" + day;
				}else {
					year = oriangeProducedate.substring(0, 4);
					month = oriangeProducedate.substring(4, 6);
					day = oriangeProducedate.substring(6, 7);
					producedate = year + "-" + month + "-0" + day;
				}
				return producedate;

				
			}

			oriangeProducedate = oriangeProducedate.replaceAll("[^x00-xff[-/ ]]", "").trim().substring(0, 8);
			String productdateType = getProducedateType(oriangeProducedate);
			
			switch(productdateType) {
//			12345.6

			case "normal" :
				year = oriangeProducedate.substring(0, 4);
				month = oriangeProducedate.substring(4, 6);
				day = oriangeProducedate.substring(6, 8);
				producedate = year + "-" + month + "-" + day;
				break;
				
			default:
				System.out.println("当前时间格式不明或者没有时间，请核查");
			}
			
			return producedate;
		}
		
	}

	private static String getProducedateType(String oriangeProducedate) {
		
		if(oriangeProducedate.length() != 8) {
			System.out.println("时间的格式不对，应该是8位长度的数字" + oriangeProducedate);
			return null;
		}
		return "normal";
	}
	
	
/**
 * 该方法用于增加天数，获取正确的日期
 */
	private static Calendar formCal = Calendar.getInstance();
	
	public static Date addDate(Date date, int day) {
		try {
//			先设置当前日期，在加上要加的天数
			formCal.setTime(date);
			formCal.add(Calendar.DATE, (day - 2));
			
			return formCal.getTime();
		}catch(Exception e) {
			return null;
		}
	}
	
//	这个方法不合适，不能在其他项目中使用。
//	public static Crawlerdetect formatDate(Crawlerdetect crawlerdetect,String arg, String type) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//		String crawlerDetectDate = null;
//		if(arg != null) {
//			crawlerDetectDate = CmiTimeUtil.format(arg);
////			通过反射的方式设置属性
//			Class clazz = crawlerdetect.getClass();
//			String methodName = "set" + type;
//			Method method = clazz.getMethod(methodName, arg.getClass());
//			method.invoke(crawlerdetect, crawlerDetectDate);
//			return crawlerdetect;
//		}
//		return null;
//	}
	
	
}